import Cookies from "js-cookie";
import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw,
  Router,
} from "vue-router";
import store from "../store";
/** vue2
 * import Vue from 'vue'
 * Vue.use(VueRouter)
 *  */
// Vue2 use : 调用的就是参数上的install方法,或者是直接调用参数.Vue.prototype.$router/$route
const routes: Array<RouteRecordRaw> = [
  {
    //登录
    path: "/login",
    name: "Login",
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/login/Login.vue"),
  },
  /*   // 动态添加路由规则事例
  {
    path: "/pms",
    name: "/pms",
    component: () =>
      import( "../views/home/HomePage.vue"),
    children: [
      //商品列表
      {
        path: "product",
        name: "product",
        component: () =>
          import("../views/pms/Product.vue"),
      },
    ],
  }, 
*/
];

const router: Router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//动态添加路由规则
const dynamicRoute = () => {
  const menus = store.getters.getNewMenus;
  // console.log(menus);
  // 参照上面动态路由事例(mock数据) 循环菜单对象
  for (let key in menus) {
    const newRoute: RouteRecordRaw = {
      path: "/" + menus[key].name,
      name: menus[key].name,
      component: () => import("../views/home/HomePage.vue"),
      redirect: "/" + menus[key].name + "/" + menus[key].children[0].name, //重定向到第一项 如 /pms/product
      children: [],
    };
    for (let i = 0; i < menus[key].children.length; i++) {
      // console.log(menus[key].children.length);
      newRoute.children?.push({
        path: menus[key].children[i].name,
        name: menus[key].children[i].name,
        component: () =>
          import(
            `../views/${menus[key].name}/${menus[key].children[i].name}.vue`
          ),
      });
    }
    router.addRoute(newRoute);
  }
  // 动态添加首页
  router.addRoute({
    path: "/",
    name: "homepage",
    component: () => import("../views/home/homePage.vue"),
    redirect: "/index",
    children: [
      {
        path: "index",
        name: "index",
        component: () => import("../views/index/index.vue"),
      },
    ],
  });
  // 动态添加首页
  router.addRoute(
    //重定向(非指定路由)
    {
      path: "/:pathMatch(.*)*", // 改版之后的写法
      name: "not-found",
      redirect: "/index",
    }
  );
};

router.beforeEach((to, from, next) => {
  const token = Cookies.get("token");
  // token为空 vuex里面的menus(权限列表为空) 重新发送请求
  if (token && store.state.menus.length === 0) {
    // 获取数据存储到vuex
    store.dispatch("updateMenus").then(() => {
      dynamicRoute(); //动态添加路由规则
      next(to);
    });
  }
  // 从登录页跳转过来
  else if (
    token &&
    store.state.menus.length !== 0 &&
    from.path === "/login" &&
    to.path === "/token"
  ) {
    // "token"只是一个标志,目的是要跳转到"/index"
    dynamicRoute(); //动态添加路由规则
    next("/index");
  } else if (!token && to.path !== "/login") {
    next("/login");
  } else if (token && to.path === "/login") {
    next(from);
  } else {
    next();
  }
});
export default router;
